#coding:utf-8

import read_configure
import requests
import urllib.request
import re
import smtplib
from email.mime.text import MIMEText
from bs4 import BeautifulSoup

#请求头字典
req_header={
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Cache-Control': 'max-age=0',
    'Connection': 'keep-alive',
    'Cookie': 'UM_distinctid=164946ef2c3260-08b768d9246d99-5e4b2519-100200-164946ef2c4405; bcolor=; font=; size=; fontcolor=; width=; CNZZDATA1263126851=614927201-1531495545-https%253A%252F%252Fwww.baidu.com%252F%7C1531560413',
    'Host': 'www.biqubook.com',
    'If-Modified-Since': 'Fri, 13 Jul 2018 10:20:32 GMT',
    'If-None-Match': '"1531477232"',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36'
}
req_url_base='http://www.biqubook.com'
req_url='http://www.biqubook.com/2_2277/'
#请求页面  params为请求参数
r=requests.get(req_url,params=req_header)
#soup转换
soup=BeautifulSoup(r.text,"html.parser")    
div=soup.find('div',id=re.compile("^info"))
#print(div)

#书名
book_name=div.find_all('h1')[0].string
print('书名：'+book_name)

info=div.find_all('p')
#作者
print(info[0].string)

#更新时间
update_time=info[2].string
print(info[2].string)

# for i in div.find_all('a'):
#     print(i.get('href')
#更新内容
info2=div.find_all('a')[2]
new_url=info2.get('href')
section_name=info2.string
update_url=req_url_base + str(new_url)
print('更新地址：'+update_url)
print('章节名称：'+section_name)
#*********************************************
u=requests.get(update_url,params=req_header)
#soup转换
soup=BeautifulSoup(u.text,"html.parser")    
section_text=soup.find('div',id="content",class_="showtxt")
#print(div.text)
#按照指定格式替换章节内容，运用正则表达式
section_text=re.sub( '\s+', '\r\n\t', section_text.text).strip('\r\n')  
#print("章节内容：\n"+section_text)

file_name=str(book_name) + '_' + str(section_name) + '.txt'
fo = open(file_name, "wb+")         #打开小说文件
# 以二进制写入章节题目 需要转换为utf-8编码，否则会出现乱码
fo.write(('\r' + section_name + '\r\n').encode('UTF-8'))  
# 以二进制写入章节内容
fo.write((section_text).encode('UTF-8'))  
fo.close()        #关闭小说文件

# 第三方 SMTP 服务
info_list = read_configure.read_file()
mail_host = "smtp.163.com"  # SMTP服务器
mail_user = info_list[0]  # 用户名
mail_pass = info_list[1]  # 密码

sender = mail_user + '@163.com'  # 发件人邮箱(最好写全, 不然会失败)
receivers = ['0']  # 接收邮件，可设置为你的QQ邮箱或者其他邮箱
receivers[0] = info_list[2]

# content = 'hello world!'
content = str(book_name) + '\n' + str(update_time) + '\n章节：' + str(section_name) + '\n' + section_text
title = '小说更新'  # 邮件主题
message = MIMEText(content, 'plain', 'utf-8')  # 内容, 格式, 编码
message['From'] = "{}".format(sender)
message['To'] = ",".join(receivers)
message['Subject'] = title

try:
    smtpObj = smtplib.SMTP_SSL(mail_host, 465)  # 启用SSL发信, 端口一般是465
    smtpObj.login(mail_user, mail_pass)  # 登录验证
    smtpObj.sendmail(sender, receivers, message.as_string())  # 发送
    print("mail has been send successfully.")
except smtplib.SMTPException as e:
    print(e)